import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import '../models/counter_model.dart';
import 'counter_detail_screen.dart';

/// Scoped Model Demo主屏幕
/// 展示如何使用ScopedModel和ScopedModelDescendant
class ScopedModelDemoScreen extends StatelessWidget {
  const ScopedModelDemoScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Scoped Model Demo'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          IconButton(
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => const CounterDetailScreen(),
                ),
              );
            },
            icon: const Icon(Icons.info_outline),
            tooltip: 'View Details',
          ),
        ],
      ),
      body: const SingleChildScrollView(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 用户信息卡片
            _UserInfoCard(),
            SizedBox(height: 16),

            // 计数器显示卡片
            _CounterDisplayCard(),
            SizedBox(height: 16),

            // 操作按钮区域
            _ActionButtonsSection(),
            SizedBox(height: 16),

            // 状态信息卡片
            _StatusInfoCard(),
          ],
        ),
      ),
    );
  }
}

/// 用户信息卡片
/// 展示如何使用ScopedModelDescendant监听特定状态
class _UserInfoCard extends StatelessWidget {
  const _UserInfoCard();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'User Information',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),

            // 使用ScopedModelDescendant监听username变化
            ScopedModelDescendant<CounterModel>(
              builder: (context, child, model) {
                return Row(
                  children: [
                    const Icon(Icons.person),
                    const SizedBox(width: 8),
                    Text('Welcome, ${model.username}!'),
                  ],
                );
              },
            ),

            const SizedBox(height: 8),

            // 用户名输入框
            TextField(
              decoration: const InputDecoration(
                labelText: 'Enter your name',
                border: OutlineInputBorder(),
              ),
              onSubmitted: (value) {
                // 使用静态方法获取model并更新用户名
                CounterModel.of(context).setUsername(value);
              },
            ),
          ],
        ),
      ),
    );
  }
}

/// 计数器显示卡片
/// 展示如何显示计数器的值和状态
class _CounterDisplayCard extends StatelessWidget {
  const _CounterDisplayCard();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            const Text(
              'Counter Value',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 使用ScopedModelDescendant监听counter变化
            ScopedModelDescendant<CounterModel>(
              builder: (context, child, model) {
                return Column(
                  children: [
                    // 显示计数器值
                    Text(
                      '${model.counter}',
                      style: Theme.of(context).textTheme.headlineLarge
                          ?.copyWith(
                            color: Theme.of(context).primaryColor,
                            fontWeight: FontWeight.bold,
                          ),
                    ),

                    const SizedBox(height: 8),

                    // 显示状态
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 12,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: _getStatusColor(model.counterStatus),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        model.counterStatus,
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'Zero':
        return Colors.grey;
      case 'Low':
        return Colors.green;
      case 'Medium':
        return Colors.orange;
      case 'High':
        return Colors.red;
      default:
        return Colors.blue;
    }
  }
}

/// 操作按钮区域
/// 展示各种操作按钮
class _ActionButtonsSection extends StatelessWidget {
  const _ActionButtonsSection();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Actions',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),

            // 基本操作按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              alignment: WrapAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(
                  onPressed: () => CounterModel.of(context).increment(),
                  icon: const Icon(Icons.add, size: 18),
                  label: const Text('+1'),
                ),
                ElevatedButton.icon(
                  onPressed: () => CounterModel.of(context).decrement(),
                  icon: const Icon(Icons.remove, size: 18),
                  label: const Text('-1'),
                ),
                ElevatedButton.icon(
                  onPressed: () => CounterModel.of(context).reset(),
                  icon: const Icon(Icons.refresh, size: 18),
                  label: const Text('Reset'),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // 批量操作按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              alignment: WrapAlignment.spaceEvenly,
              children: [
                OutlinedButton(
                  onPressed: () => CounterModel.of(context).addMultiple(5),
                  child: const Text('+5'),
                ),
                OutlinedButton(
                  onPressed: () => CounterModel.of(context).addMultiple(10),
                  child: const Text('+10'),
                ),
                OutlinedButton(
                  onPressed: () => CounterModel.of(context).addMultiple(100),
                  child: const Text('+100'),
                ),
              ],
            ),

            const SizedBox(height: 12),

            // 异步操作按钮
            ScopedModelDescendant<CounterModel>(
              builder: (context, child, model) {
                return SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: model.isLoading
                        ? null
                        : () => model.incrementAsync(),
                    icon: model.isLoading
                        ? const SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(strokeWidth: 2),
                          )
                        : const Icon(Icons.cloud_upload),
                    label: Text(model.isLoading ? 'Loading...' : 'Async +1'),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

/// 状态信息卡片
/// 展示如何监听多个状态变化
class _StatusInfoCard extends StatelessWidget {
  const _StatusInfoCard();

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Status Information',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),

            // 使用ScopedModelDescendant监听所有状态
            ScopedModelDescendant<CounterModel>(
              builder: (context, child, model) {
                return Column(
                  children: [
                    _buildStatusRow(
                      'Current Value',
                      '${model.counter}',
                      Icons.numbers,
                    ),
                    _buildStatusRow('Status', model.counterStatus, Icons.info),
                    _buildStatusRow('User', model.username, Icons.person),
                    _buildStatusRow(
                      'Loading',
                      model.isLoading ? 'Yes' : 'No',
                      model.isLoading ? Icons.hourglass_empty : Icons.check,
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusRow(String label, String value, IconData icon) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          Icon(icon, size: 20),
          const SizedBox(width: 8),
          Text('$label: '),
          Text(value, style: const TextStyle(fontWeight: FontWeight.bold)),
        ],
      ),
    );
  }
}
